import React, { Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import printJS from 'print-js';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { Card, Button, Spin } from 'antd';

import '@ant-design/compatible/assets/index.css';
import styles from './index.less';

interface PrintElemProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterBatchPrint: any;
  detailInfo: any;
  INITINFO: any;
  spinning: boolean;
  location: { query: any };
}

@connect(({ logisCenterBatchPrint: { detailInfo, spinning }, common: { INITINFO } }: any) => ({
  spinning,
  detailInfo,
  INITINFO,
}))
class PrintElemInfo extends React.Component<PrintElemProps> {
  componentDidMount() {
    const {
      location: {
        query: { id },
      },
    } = this.props;
    if (id) {
      this.handleDetail(id);
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterBatchPrint/clear',
      payload: {},
    });
  }

  handleDetail = (id: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterBatchPrint/detail',
      payload: {
        batchId: id,
        pageIndex: 1,
        pageSize: 9999,
      },
    });
  };

  // 打印明细
  handlePrintOrder = () => {
    printJS({
      printable: 'billDetails',
      type: 'html',
      targetStyles: ['*'],
      onPrintDialogClose: () => '关闭',
      onError: error => error,
    });
  };

  // 取消打印
  handlePrint = () => {
    router.goBack();
  };

  renderTable = (payment: any, paymentList: any, type: any) => (
    <Fragment>
      <thead>
        <tr className={styles.title}>
          <th colSpan={24} className={styles.borderRight}>
            <span>
              {type === 1 ? '已付款订单' : '未付款订单'}({paymentList.length})
            </span>
            <span className={styles.unit}>金额单位:（元）</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr className={styles.lineHeight}>
          <td className={styles.borderLeft}>序号</td>
          <td>快递单号</td>
          <td>金额</td>
          <td>序号</td>
          <td>快递单号</td>
          <td>金额</td>
          <td>序号</td>
          <td>快递单号</td>
          <td>金额</td>
          <td>序号</td>
          <td>快递单号</td>
          <td>金额</td>
        </tr>
        {payment.map((item: any, index: number) => (
          <tr key={Math.random()} className={styles.lineHeight}>
            {item.map((newItem: any, newIndex: number) => (
              <Fragment key={newItem.id + Math.random()}>
                <td>NO.{index * 4 + newIndex + 1}</td>
                <td>{newItem.expCode}</td>
                <td>{(newItem.payment / 100).toFixed(2)}</td>
              </Fragment>
            ))}
            {item.length < 4
              && [...Array(4 - item.length).keys()].map((newItem: any) => (
                <Fragment key={newItem}>
                  <td />
                  <td />
                  <td />
                </Fragment>
              ))}
          </tr>
        ))}
      </tbody>
    </Fragment>
  );

  render() {
    const {
      detailInfo: { list = [] },
      spinning,
      location: {
        query: {
          logisName,
          expressName,
          seqNo,
          batchDate,
          scanCount,
          deliveredCount,
          paymentAmount,
        },
      },
    } = this.props;

    const paymentList = list.filter((item: any) => item.payment <= 0);
    const noPaymentList = list.filter((item: any) => item.payment > 0);

    const new_paymentList = [...paymentList];
    const payMapCount = Math.ceil(new_paymentList.length / 4);
    const payment = [];

    while (payment.length < payMapCount) {
      payment.push(new_paymentList.splice(0, 4));
    }

    const new_noPaymentList = [...noPaymentList];
    const noPayment = [];
    const noPayMapCount = Math.ceil(new_noPaymentList.length / 4);

    while (noPayment.length < noPayMapCount) {
      noPayment.push(new_noPaymentList.splice(0, 4));
    }

    return (
      <Fragment>
        <PageHeader />
        <Card id="card" bordered={false}>
          <Spin spinning={spinning}>
            <div className={styles.buttons} id="buttons">
              <Button type="primary" className={styles.print} onClick={this.handlePrintOrder}>
                打印
              </Button>
              <Button onClick={this.handlePrint}>取消</Button>
            </div>

            <div id="billDetails">
              <table
                className="batchTable"
                cellPadding="0"
                cellSpacing="0"
                style={{
                  width: '100%',
                  borderCollapse: 'collapse',
                  textAlign: 'center',
                  fontSize: 12,
                }}
              >
                <thead>
                  <tr>
                    <td
                      colSpan={6}
                      style={{
                        fontSize: '20px',
                        fontWeight: 'bold',
                        borderCollapse: 'collapse',
                        lineHeight: '200%',
                        borderRight: '1px solid #ADADAD',
                      }}
                    >
                      《{logisName}接驳明细单》
                    </td>
                  </tr>
                </thead>

                <tbody>
                  <tr>
                    <td
                      colSpan={6}
                      style={{
                        paddingLeft: 20,
                        color: 'red',
                        textAlign: 'left',
                      }}
                    >
                      【警示！】请快递公司在接驳前提前剔除易碎件、生鲜品、保质期短的物品，
                      如未提前剔除或告知，造成收件人退件、投诉、索赔，由快递公司自负。
                      若快递公司提前告知我方收件人已承诺收件，且已签订《承诺单》，我方可接驳。
                    </td>
                  </tr>
                  <tr className={styles.lineHeight}>
                    <td className={styles.borderLeft}>快递公司</td>
                    <td>{expressName}</td>
                    <td>接驳批次</td>
                    <td>第{seqNo}批次</td>
                    <td>接驳时间</td>
                    <td>{batchDate}</td>
                  </tr>
                  <tr className={styles.lineHeight}>
                    <td className={styles.borderLeft}>快件总量</td>
                    <td>{scanCount}</td>
                    <td>其中:货到付款</td>
                    <td
                      colSpan={3}
                      style={{
                        fontWeight: 600,
                      }}
                    >
                      {scanCount - deliveredCount}件 金额:
                      {(paymentAmount / 100).toFixed(2)}
                    </td>
                  </tr>
                  <tr className={styles.lineHeight}>
                    <td className={styles.borderLeft}>快递公司确认签字</td>
                    <td colSpan={2} />
                    <td>近邻宝确认签字/签字日期</td>
                    <td colSpan={2} />
                  </tr>
                </tbody>
              </table>
              <table
                className="batchTable"
                cellPadding="0"
                cellSpacing="0"
                style={{
                  width: '100%',
                  marginBottom: '24px',
                  borderCollapse: 'collapse',
                  fontSize: 12,
                  textAlign: 'center',
                }}
              >
                {this.renderTable(payment, paymentList, 1)}
                {this.renderTable(noPayment, noPaymentList, 2)}
              </table>
            </div>
          </Spin>
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<PrintElemProps>()(PrintElemInfo);
